﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.Linq;

namespace YABE.Models
{
	public class TagDL
	{
		static public List<Tag> AddTags(string[] tagArray)
		{
			List<Tag> tagList = new List<Tag>();

			using (YabeDataContext context = YabeDataManager.Instance.DataContext)
			{
				foreach (string tagName in tagArray)
				{
					Tag t = context.Tags.SingleOrDefault(c =>
									c.TagName.ToLower() == tagName.Trim().ToLower() );
					if (t == null)
					{
						t = new Tag()//tag does not exist in db
						{
							TagName = tagName.Trim(),
						};
						context.Tags.InsertOnSubmit(t);
					}
					tagList.Add(t);			
				}

				try
				{
					context.SubmitChanges(ConflictMode.ContinueOnConflict);

				}
				catch (ChangeConflictException)
				{
					context.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues); //User values will be keeped on the resolution
				}
			}

			return tagList;
		}

		static public List<Tag> GetTags()
		{
			using (YabeDataContext context = YabeDataManager.Instance.DataContext)
			{
				return context.Tags.ToList();
			}
		}

		static public List<vwTagCount> GetTagCounts()
		{
			List<vwTagCount> tagCloud;
			using (YabeDataContext context = YabeDataManager.Instance.DataContext)
			{
				tagCloud = context.vwTagCounts.ToList();
			}

			if (tagCloud == null || tagCloud.Count == 0)
				return tagCloud;

			double mean = 0;
			double stdDev = 0;
			
			// calculate mean
			foreach (vwTagCount tag in tagCloud)
			{
				mean = mean + tag.TagCount ?? 0;
			}

			mean = mean / tagCloud.Count;

			// calculate std
			foreach (vwTagCount tag in tagCloud)
			{
				stdDev = stdDev + Math.Pow(tag.TagCount ?? 0 - mean,2);
			}

			stdDev = Math.Sqrt(stdDev / tagCloud.Count);

			// set the sizes based on standard deviation
			foreach (vwTagCount tag in tagCloud)
			{
				double factor = (tag.TagCount ?? 0 - mean) / stdDev;
				if(	factor <= -2*stdDev )
					tag.TagSize = 60;
				else if ( -2*stdDev < factor && factor <= -1*stdDev )
					tag.TagSize = 80;
				else if (-1 * stdDev < factor && factor <= -0.5 * stdDev)
					tag.TagSize = 100;
				else if (-0.5 * stdDev < factor && factor < 0.5 * stdDev)
					tag.TagSize = 120;
				else if (0.5 * stdDev <= factor && factor < 1 * stdDev)
					tag.TagSize = 140;
				else if (1 * stdDev <= factor && factor < 2 * stdDev)
					tag.TagSize = 160;
				else if ( factor >= 2*stdDev )
					tag.TagSize = 180;
			}

			return tagCloud;
		}
	}
}
